package project.order.work;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;

import net.sf.json.JSONObject;

public class WxOpenIdHelperLocal {

    public static String getCodeUrl(String state) {

//        String redirect_uri = "http://www.shinner.cn/root/public/orderAction!view.action";
//        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + AccessTokenThread.appid + "&redirect_uri="
//                + redirect_uri + "&response_type=code&scope=snsapi_base&state=" + state + "#wechat_redirect";
        
    	String url = "http://127.0.0.1:8099/root/public/orderAction!view.action?state="+state;
        return url;
    }
    public static String getSingleCodeUrl(String state) {

//      String redirect_uri = "http://www.shinner.cn/root/public/orderSingleAction!view.action";
//      String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + AccessTokenThread.appid + "&redirect_uri="
//              + redirect_uri + "&response_type=code&scope=snsapi_base&state=" + state + "#wechat_redirect";
      
  	String url = "http://127.0.0.1:8099/root/public/orderSingleAction!view.action?state="+state;
      return url;
  }
    /**
    *@author Kenshinbo@163.com
    *@描述：获取用户授权URL
    *@param state
    *@return 
    *@version  WxOpenIdHelper.java,v 1.1 Jan 30, 2015 3:14:05 PM KB
    */
    public static String getUserCodeUrl(String state) {

        String redirect_uri = "http://www.mrshine.cn/root/public/orderAction!userAuthView.action";
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + AccessTokenThread.appid + "&redirect_uri="
                + redirect_uri + "&response_type=code&scope=snsapi_userinfo&state=" + state + "#wechat_redirect";
        
//    	String url = "http://127.0.0.1:8099/root/public/orderAction!view.action?state="+state;
        return url;
    }
/**
*@author Kenshinbo@163.com
*@描述：通过授权的access_code获取到用户的授权信息
*@param str
*@return 
*@version  WxOpenIdHelper.java,v 1.1 Jan 30, 2015 3:29:24 PM KB
*/
public static JSONObject  getUserAuthInfo2(String openid,String access_token) {
	 		JSONObject json=null;//初值
            //send to 微信
            try {
                URL url=new URL("https://api.weixin.qq.com/sns/userinfo?access_token="+access_token+"&openid="+openid+"&lang=zh_CN");
                
                trustAllHttpsCertificates();
                HttpsURLConnection.setDefaultHostnameVerifier(hv);
                
                HttpURLConnection conn=(HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");
                conn.setDoOutput(false);
                //获取InputStream的值
                InputStream is=null;
               
                try {
                    is=conn.getInputStream();
                    String sReturn=new String(readInputStream(is),("UTF-8"));
                    System.out.println("WxOpenIdHelper get winxin userAuthInfo:"+sReturn);
                    is.close();
                    //获得json对象，catch中的异常也需要使用这个值
                    json=JSONObject.fromObject(sReturn);
                    

                }
                catch (Exception ex) {
                    if (json!=null) {
                        System.out.println((Integer) json.get("errcode"));
                        System.out.println((String) json.get("errmsg"));
                        System.out.println("json:"+json.toString());
                    }
                    ex.printStackTrace();
                }
            }
            catch (Exception ex) {
                ex.printStackTrace();
            }

            return json;

    }
 /**
*@author Kenshinbo@163.com
*@描述：获取授权的用户信息
*@param code
*@return 
*@version  WxOpenIdHelper.java,v 1.1 Jan 30, 2015 3:28:32 PM KB
*/
public static JSONObject  getUserAuthInfo(String code) {
        
        String openid = null;
        String access_token = null;
        JSONObject userInfo = null;
            //send to 微信
            try {
                URL url=new URL("https://open.weixin.qq.com/connect/oauth2/authorize?appid="+AccessTokenThread.appid+"&secret="+AccessTokenThread.secret+"&code="+code+"&grant_type=authorization_code");
                
                trustAllHttpsCertificates();
                HttpsURLConnection.setDefaultHostnameVerifier(hv);
                
                HttpURLConnection conn=(HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");
                conn.setDoOutput(false);
                //获取InputStream的值
                InputStream is=null;
                JSONObject json=null;//初值
                try {
                    is=conn.getInputStream();
                    String sReturn=new String(readInputStream(is),("UTF-8"));
                    System.out.println("WxOpenIdHelper get winxin userAuthCode:"+sReturn);
                    is.close();
                    //获得json对象，catch中的异常也需要使用这个值
                    json=JSONObject.fromObject(sReturn);
                    //获取授权的access_token
                    access_token=(String) json.get("access_token");
                    openid=(String) json.get("openid");
                    //获取用户信息
                    userInfo = getUserAuthInfo2(access_token,openid);
                }
                catch (Exception ex) {
                    if (json!=null) {
                        System.out.println((Integer) json.get("errcode"));
                        System.out.println((String) json.get("errmsg"));
                        System.out.println("json:"+json.toString());
                    }
                    ex.printStackTrace();
                }
            }
            catch (Exception ex) {
                ex.printStackTrace();
            }

            return userInfo;

    }
    public static String  getOpenId(String code) {
        
        String openid = null;
      
            //send to 微信
            try {
                URL url=new URL("https://api.weixin.qq.com/sns/oauth2/access_token?appid="+AccessTokenThread.appid+"&secret="+AccessTokenThread.secret+"&code="+code+"&grant_type=authorization_code");
                
                trustAllHttpsCertificates();
                HttpsURLConnection.setDefaultHostnameVerifier(hv);
                
                HttpURLConnection conn=(HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");
                conn.setDoOutput(false);
                //获取InputStream的值
                InputStream is=null;
                JSONObject json=null;//初值
                try {
                    is=conn.getInputStream();
                    String sReturn=new String(readInputStream(is),("UTF-8"));
                    System.out.println("WxOpenIdHelper get winxin Message:"+sReturn);
                    is.close();
                    //获得json对象，catch中的异常也需要使用这个值
                    json=JSONObject.fromObject(sReturn);
                    //设置静态变量
                    openid=(String) json.get("openid");
                    System.out.println("openid:"+openid);

                }
                catch (Exception ex) {
                    if (json!=null) {
                        System.out.println((Integer) json.get("errcode"));
                        System.out.println((String) json.get("errmsg"));
                        System.out.println("json:"+json.toString());
                    }
                    ex.printStackTrace();
                }
            }
            catch (Exception ex) {
                ex.printStackTrace();
            }

            return openid;

    }


public static byte[] readInputStream(InputStream inStream){
    byte[] data=null;
    try {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while( (len = inStream.read(buffer)) !=-1 ){
            outStream.write(buffer, 0, len);
        }
        data = outStream.toByteArray();//
        outStream.close();
        inStream.close();

    }
    catch(Exception ex) {
        ex.printStackTrace();
    }
    return data;
}

//以下开始时https的信任默认代码
static HostnameVerifier hv = new HostnameVerifier() {
    public boolean verify(String urlHostName, SSLSession session) {
        System.out.println("Warning: URL Host: " + urlHostName + " vs. "
                           + session.getPeerHost());
        return true;
    }
};

 private static void trustAllHttpsCertificates() throws Exception {
     javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1];
     javax.net.ssl.TrustManager tm = new Mitm();
     trustAllCerts[0] = tm;
     javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext.getInstance("SSL");
     sc.init(null, trustAllCerts, null);
     javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
 }

 static class Mitm implements javax.net.ssl.TrustManager,javax.net.ssl.X509TrustManager {
     public java.security.cert.X509Certificate[] getAcceptedIssuers() {
         return null;
     }

     public boolean isServerTrusted(java.security.cert.X509Certificate[] certs) {
         return true;
     }

     public boolean isClientTrusted(java.security.cert.X509Certificate[] certs) {
        return true;
     }

     public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) throws java.security.cert.CertificateException {
        return;
     }

     public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) throws java.security.cert.CertificateException {
         return;
     }
 }

}
